package org.budo.redis.jdbc.driver.statement.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;
import org.budo.support.lang.util.MapUtil;

/**
 * SHOW databases
 * 
 * @author lmw
 */
public class SHOW_DATABASES extends AbstractRedisStatement {
    private static final String DB_COUNT_SQL = "SELECT CONFIG_GET('databases')";

    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        Integer databases = this.getDatabases(preparedStatement); // 执行一次查询，得到Db数量

        Map[] mapArray = new Map[databases]; //
        for (int i = 0; i < databases; i++) {
            mapArray[i] = MapUtil.stringObjectMap("DataBase", i);
        }

        String[] columnNames = new String[] { "DataBase" };
        ResultSet resultSet = new MapArrayResultSet(columnNames, mapArray);
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }

    private Integer getDatabases(PreparedStatement preparedStatement) {
        try {
            Connection connection = preparedStatement.getConnection();
            PreparedStatement prepareStatement = connection.prepareStatement(DB_COUNT_SQL);
            ResultSet resultSet = prepareStatement.executeQuery();
            while (resultSet.next()) {
                prepareStatement.close();
                return resultSet.getInt("value");
            }

            throw new RuntimeException("#43 getDatabases error");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
